package com.nightsoul.jdktools.test.classreplace;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.lang.instrument.ClassDefinition;
import java.lang.instrument.Instrumentation;

public class MyAgent {
	
	//agentArgs就是VirtualMachine.loadAgent()的第二个参数
	public static void agentmain(String agentArgs, Instrumentation instrumentation) {
		try {
			System.out.println("args: " + agentArgs);
			System.out.println("重新定义 test.User -- 开始");
			//把新的User类文件的内容读出来
			File f = new File(agentArgs);
			byte[] reporterClassFile = new byte[(int) f.length()];
			DataInputStream in = new DataInputStream(new FileInputStream(f));
			in.readFully(reporterClassFile);
			in.close();
			
			ClassDefinition classDefinition = new ClassDefinition(User.class, reporterClassFile);
			instrumentation.redefineClasses(classDefinition);
			System.out.println("重新定义 test.User  -- 完成");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
